#include "mainwindow.h"
#include <QDir>
#include <QString>
#include <QActionGroup>
#include <QMenuBar>
#include <QSplitter>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QFileDialog>
#include <QInputDialog>
#include <QDirIterator>
#ifdef _WIN32
#include <windows.h>
#include "dynamicmapmanagewindow.h"
#include "JlCompress.h"
#endif
#include <QProcess>
#include <QEventLoop>
#include "componentwidget.h"
#include "stationwidget.h"
#include "structurewidget.h"
#include "attributewidget.h"
#include "showwidget.h"
#include "guidewidget.h"
#include "editwidget.h"
#include "configwidget.h"

#include <iostream>
#include <fstream>
#include <QIcon>
using namespace std;

PtrDynamicMapParam myapp::mDynamicMapParam = new DynamicMapParam;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent) 
{
    setWindowModality(Qt::WindowModal);
    setWindowFlags( windowFlags() & Qt::Window & Qt::WindowMinMaxButtonsHint);
    resize((Screen::GetScreenWidth())>>1, (Screen::GetScreenHeight())>>1);
    setWindowState(Qt::WindowMaximized);
    setWindowIcon(QIcon(":/img/logo.png"));

    menu_bar = this->menuBar();
    menu_file = menu_bar-> addMenu(QObject::tr("File"));
    menu_source = menu_bar->addMenu(QObject::tr("Source"));

    QAction *action_new = menu_file->addAction(QObject::tr("New Project"));
    QAction *action_new_file = menu_file->addAction(QObject::tr("New File"));
    QAction *action_open = menu_file->addAction(QObject::tr("Open Project"));
    QAction *action_save = menu_file->addAction(QObject::tr("Save Project"));
    QAction *action_exit = menu_file->addAction(QObject::tr("Exit"));

    QAction *action_source_all = menu_source->addAction(QObject::tr("All Loading"));
    //QAction *action_source_incremental = menu_source->addAction(QObject::tr("Incremental Loading"));
    //QAction *action_source_update = menu_source->addAction(QObject::tr("Update Attritube by Idtype"));

    QAction *auto_generate_from_up = menu_source->addAction(QObject::tr("Auto Generate From Up"));
    QAction *auto_generate_arrive_from_one = menu_source->addAction(QObject::tr("Auto Generate Arrive All Station From One"));
    QAction *action_source_bale = menu_source->addAction(QObject::tr("Package"));

//    QAction *action_simulate_minual = menu_simulate->addAction(QObject::tr("Minual Simulate"));
//    QMenu *menu_simulate_auto = menu_simulate->addMenu(QObject::tr("Auto Simulate"));
//    QAction *action_simulate_up = menu_simulate_auto->addAction(QObject::tr("Simulate Up"));
//    QAction *action_simulate_up_mirror = menu_simulate_auto->addAction(QObject::tr("Simulate Up Mirror"));
//    QAction *action_simulate_down = menu_simulate_auto->addAction(QObject::tr("Simulate Down"));
//    QAction *action_simulate_down_mirror = menu_simulate_auto->addAction(QObject::tr("Simulate Down Mirror"));
//    QAction *action_simulate_pause = menu_simulate->addAction(QObject::tr("Pause Simulate"));

    QFont f = menu_file->font();
    f.setPixelSize(16);
    menu_file->setFont(f);
    menu_source->setFont(f);
    menu_bar->setFont(f);
    setMenuBar(menu_bar);

    QSplitter *splitterMain = new QSplitter(Qt::Horizontal, this);
    splitterMain->setOpaqueResize(true);
    splitterMain->setHandleWidth(1);
    splitterMain->setChildrenCollapsible(false);

    QSplitter *splitter_left = new QSplitter(Qt::Vertical, splitterMain);
    splitter_left->setOpaqueResize(true);
    splitter_left->setHandleWidth(1);
    splitter_left->setChildrenCollapsible(false);

    QSplitter *splitter_middle = new QSplitter(Qt::Vertical, splitterMain);
    splitter_middle->setOpaqueResize(true);
    splitter_middle->setHandleWidth(1);
    splitter_middle->setChildrenCollapsible(false);

    QSplitter *splitter_right = new QSplitter(Qt::Vertical, splitterMain);
    splitter_right->setOpaqueResize(true);
    splitter_right->setHandleWidth(1);
    splitter_right->setChildrenCollapsible(false);

    //左下角控件列表
    component_widget = new ComponentWidget;
    //左上角树形结
    station_widget = new StationWidget;
    //右上角单图中单个控件名称
    struture_widget = new StructureWidget;
    //右下角单图中单个控件属性
    attribute_widget = new AttributeWidget;
    attribute_widget->setStyleSheet("background-color:rgb(240, 240, 240)");
    //中间显示窗口
    show_widget = new ShowWidget;
    //配置窗口
    config_widget = new ConfigWidget;
    //config_widget->setStyleSheet("background-color:blue");

    splitter_left->addWidget(station_widget);
    splitter_left->addWidget(component_widget);
    splitter_left->setStretchFactor(0, 1);
    splitter_left->setStretchFactor(1, 1);
    splitter_left->setContentsMargins(0, 0, 0, 0);

    splitter_right->addWidget(struture_widget);
    splitter_right->addWidget(attribute_widget);
    splitter_right->setStretchFactor(0, 1);
    splitter_right->setStretchFactor(1, 1);
    splitter_right->setContentsMargins(0, 0, 0, 0);

    splitter_middle->addWidget(show_widget);
    splitter_middle->addWidget(config_widget);
    splitter_middle->setStretchFactor(0, 3);
    splitter_middle->setStretchFactor(1, 1);
    splitter_middle->setContentsMargins(0, 0, 0, 0);

    splitterMain->addWidget(splitter_left);
    splitterMain->addWidget(splitter_middle);
    splitterMain->addWidget(splitter_right);
    splitterMain->setStretchFactor(0, 0);
    splitterMain->setStretchFactor(1, 8);
    splitterMain->setStretchFactor(2, 0);
    setCentralWidget(splitterMain);

    action_new->setShortcut(QKeySequence::New);

    action_new_file->setShortcut(tr("ctrl+f"));//组合快捷键
    action_open->setShortcut(QKeySequence::Open);
    action_save->setShortcut(QKeySequence::Save);
    action_exit->setShortcut(QKeySequence::Close);

    action_group = new QActionGroup(this);

    action_group->addAction(action_new);
    action_group->addAction(action_new_file);
    action_group->addAction(action_open);
    action_group->addAction(action_save);
    action_group->addAction(action_exit);

    action_group->addAction(action_source_all);
    action_group->addAction(auto_generate_from_up);
    action_group->addAction(auto_generate_arrive_from_one);
    action_group->addAction(action_source_bale);

//    action_group->addAction(action_simulate_minual);
//    action_group->addAction(action_simulate_pause);

//    action_group->addAction(action_simulate_up);
//    action_group->addAction(action_simulate_up_mirror);
//    action_group->addAction(action_simulate_down);
//    action_group->addAction(action_simulate_down_mirror);

    connect(action_group, &QActionGroup::triggered, this, &MainWindow::menu_action);

    connect(component_widget, &ComponentWidget::sgl_to_mainwindow_for_create_item, this, &MainWindow::slt_create_item);
    connect(station_widget, &StationWidget::signal_select_file, this, &MainWindow::set_curr_show_filename);

    connect(show_widget, &ShowWidget::sgl_to_structurewidget_to_select, struture_widget,  &StructureWidget::slt_select_item);
    connect(show_widget, &ShowWidget::sgl_to_attributewidget_to_show,   attribute_widget, &AttributeWidget::slt_show_attribute);
    connect(show_widget, &ShowWidget::signal_delete, this, &MainWindow::delete_object);
    connect(show_widget, &ShowWidget::signal_copy,   this, &MainWindow::copy_object);

    connect(struture_widget, &StructureWidget::signal_list_to_graphics, show_widget, &ShowWidget::signal_list_to_graphics);

    connect(attribute_widget, &AttributeWidget::signal_update_graphics, show_widget, &ShowWidget::signal_update_graphics);

    connect(station_widget, &StationWidget::signal_select_file, show_widget,     &ShowWidget::slt_show_widget_by_file);
    connect(station_widget, &StationWidget::signal_select_file, struture_widget, &StructureWidget::ShowStructue);
    connect(station_widget, &StationWidget::signal_select_file, attribute_widget, &AttributeWidget::cancel_attribute);

    connect(config_widget, &ConfigWidget::reload_from_config, this, &MainWindow::ReloadMainWayFromConfig);

    setContentsMargins(0, 0, 0, 0);

    mCurrShowFilename = "";

    //Test auto open project xiefei 20210928
//    open_project("D:\\linuxshare\\vm_project\\INT_GMMS\\test_project\\test_project.json");
}

MainWindow::~MainWindow()
{

}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (myapp::mDynamicMapParam->mMapObjectShow.size() == 0)
        qApp->quit();

    QMessageBox qst(QMessageBox::Question, tr("Question"), tr("save all to xml ?"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
    qst.setButtonText(QMessageBox::Yes, tr("yes"));
    qst.setButtonText(QMessageBox::No, tr("no"));
    qst.setButtonText(QMessageBox::Cancel, tr("cancel"));
    int ret = qst.exec();
    if (ret == QMessageBox::Yes)
        saveaAllProject();
    if (ret == QMessageBox::Cancel)
    {
        event->ignore();
        return;
    }
    //关闭窗口
    event->accept();
    qApp->quit();
}

void MainWindow::set_curr_show_filename(QString file_name)
{
    mCurrShowFilename = file_name;
}

void MainWindow::clearSouece()
{
    QString path =  QString("%1/img").arg(myapp::mDynamicMapParam->m_project_path);

    if (!myapp::isDirExist(path))
        return;
    QDir dir(path);

    QDirIterator DirsIterator(path, QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot, QDirIterator::NoIteratorFlags);
    while (DirsIterator.hasNext())
    {
        if (!dir.remove(DirsIterator.next())) //删除文件操作如果返回否，那它就是目录
        {
             QDir(DirsIterator.filePath()).removeRecursively(); //删除目录本身以及它下属所有的文件及目录
        }
    }
}

void MainWindow::createSourceFilder()
{
    QDir folder(myapp::mDynamicMapParam->m_project_path);
    createFoler(&folder, QString("%1/xml").arg(myapp::mDynamicMapParam->m_project_path));
    createFoler(&folder, QString("%1/img").arg(myapp::mDynamicMapParam->m_project_path));
}

void MainWindow::createEditWidgets()
{
    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        QString fileNameAndSuffix = it.key();
        if (ZERO != fileNameAndSuffix.right(3).compare("xml"))
            continue;

        EditWidget *edit = new EditWidget(fileNameAndSuffix, QSize(myapp::mDynamicMapParam->m_width, myapp::mDynamicMapParam->m_height));
        if (edit) {
            edit->setPath(myapp::mDynamicMapParam->m_project_path);
            edit->setVisible(false);
            it.value() = edit;
        }
    }
}

bool MainWindow::isCreatedProject()
{
    if (myapp::mDynamicMapParam->m_project_path == "" || myapp::mDynamicMapParam->m_project_name == "")
    {
         QMessageBox::warning(this, QObject::tr("Warning"), QObject::tr("Please first create project!"));
         return false;
    }
    return true;
}

void MainWindow::menu_action(QAction *action)
{
    if (ZERO == action->text().compare(QObject::tr("Save Project")))
    {
        if (!isCreatedProject())
            return;
        save_project();
    }
    else if (ZERO == action->text().compare(QObject::tr("New File")))
    {
        if (!isCreatedProject())
            return;
        create_file();
    }
    else if (ZERO == action->text().compare(QObject::tr("New Project")))
    {
        create_project();
    }
    else if (ZERO == action->text().compare(QObject::tr("Open Project")))
    {
        open_project();
    }
    else if (ZERO == action->text().compare(QObject::tr("Exit")))
    {
        close();
    }
    else if (ZERO == action->text().compare(QObject::tr("All Loading")))
    {
        if (!isCreatedProject())
            return;

        QString dir = myapp::isDirExist(myapp::mDynamicMapParam->m_project_path) == true ? myapp::mDynamicMapParam->m_project_path : QDir::currentPath();
        QString title = QObject::tr("please select directory!");
        QString path = QFileDialog::getExistingDirectory(this, title, dir);
        if (path == "")
        {
            //QMessageBox::warning(this, QObject::tr("waring"), QObject::tr("path is empty! please select again"));
            return;
        }
        else if (!myapp::isDirExist(path))
        {
            QMessageBox::warning(this, QObject::tr("error"), QObject::tr("the directory does not exist!"));
            return;
        }

        clearSouece();

        bool ret = false;
        ret = myapp::copyDirectoryFiles(path, QString("%1/img").arg(myapp::mDynamicMapParam->m_project_path), true);

        if (!ret)
        {
            LOG_QDEBUG << "all loading copy file has error!";
        }
        else
        {
            EditWidget* edit = show_widget->getEditWidget();
            if (edit != NULL)
                edit->show_component();
        }

    }
    else if (ZERO == action->text().compare(QObject::tr("Incremental Loading")))
    {
        if (!isCreatedProject())
            return;

        QString dir = myapp::isDirExist(myapp::mDynamicMapParam->m_project_path) == true ? myapp::mDynamicMapParam->m_project_path : QDir::currentPath();
        QString title = QObject::tr("please select directory");
        QString path = QFileDialog::getExistingDirectory(this, title, dir);
        if (path == "")
        {
            QMessageBox::warning(this, QObject::tr("waring"), QObject::tr("path is empty! please select again"));
            return;
        }
        else if (!myapp::isDirExist(path))
        {
            QMessageBox::warning(this, QObject::tr("error"), QObject::tr("the directory does not exist!"));
            return;
        }

        bool ret = false;

        ret = myapp::copyDirectoryFiles(path, QString("%1/img").arg(myapp::mDynamicMapParam->m_project_path), true);

        if (!ret)
            LOG_QDEBUG << "Incremental loading copy file has error!";
    }
    else if (ZERO == action->text().compare(QObject::tr("Package")))
    {
        if (!isCreatedProject())
            return;

        QString fullpath = QString("%1/res").arg(myapp::mDynamicMapParam->m_project_path);

        if (myapp::isDirExist(fullpath))
        {
            QString zip_file = QString("%1/res.zip").arg(myapp::mDynamicMapParam->m_project_path);
             bool ret = false;
             ret = JlCompress::compressDir(zip_file, fullpath);
             if (ret)
                QMessageBox::warning(this, QObject::tr("prompt"), QObject::tr("zip res success!"));
             else
                QMessageBox::warning(this, QObject::tr("error"), QObject::tr("zip res error!"));
        }
        else
        {
            QMessageBox::warning(this, QObject::tr("waring"), QObject::tr("no project source!"));
            return;
        }
    }
    else if (ZERO == action->text().compare(QObject::tr("Auto Generate From Up")))
    {
        AutoGenerateFromUp();
        AutoGenerateArriveOneFromUp();
    }
    else if (ZERO == action->text().compare(QObject::tr("Auto Generate Arrive All Station From One")))
    {
        AutoGenerateArriveAllStationFromOne();
    }

    else
    {

    }
}

void MainWindow::delete_object(QString id)
{
    attribute_widget->delete_attribute(id);
    struture_widget->delete_item(id);
}

//暂时不支持拷贝
void MainWindow::copy_object(QString file_name, QString object_name, QString random)
{
    if (random == "")
        return;

    struture_widget->CreateStructure(file_name, object_name, random);
}

void MainWindow::AutoGenerateArriveAllStationFromOne()
{
    //只处理第二个站点到最后一个站点的到站图
    //清空上下行的镜像和非镜像界面的所有edit上的控件，并重新根据上行生成，适合上行增删控件或者大面积改位置之后重新生成
    if (myapp::mDynamicMapParam->mMapObjectShow.size() == 0)
        return;

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");

        QString uiType = list.at(ParamType);

        if (uiType.contains(ArriveFlag))
        {
            if (list.size() < 3)
            {
                LOG_QDEBUG << "arrive xml do not contains stid, this is new verson";
                QMessageBox::warning(this, tr("Warning"), tr("arrive xml do not contains stid, this is new verson"), QMessageBox::Yes);
                return;
            }
            if (1 != list.at(2).toInt())
            {
                if (it.value())
                {
                    EditWidget *edit = qobject_cast<EditWidget *>(it.value());
                    if (edit == NULL) continue;
                    edit->ClearVector();
                    struture_widget->DeleteStructureData(it.key());
                    attribute_widget->cancel_attribute();
                }
            }
        }
    }

    GenerateArriveFromStationOne();
}

void MainWindow::GenerateArriveFromStationOne()
{
    EditWidget *arrive_up_widget_1 = qobject_cast<EditWidget *>(myapp::mDynamicMapParam->mMapObjectShow["arrive_1_1.xml"]);
    EditWidget *arrive_up_mirror_widget_1 = qobject_cast<EditWidget *>(myapp::mDynamicMapParam->mMapObjectShow["arrive_1_1_mirror.xml"]);
    EditWidget *arrive_down_widget_1 = qobject_cast<EditWidget *>(myapp::mDynamicMapParam->mMapObjectShow["arrive_2_1.xml"]);
    EditWidget *arrive_down_mirror_widget_1 = qobject_cast<EditWidget *>(myapp::mDynamicMapParam->mMapObjectShow["arrive_2_1_mirror.xml"]);
    if ((NULL == arrive_up_widget_1) || (NULL == arrive_up_mirror_widget_1)
            || (NULL == arrive_down_widget_1) || (NULL == arrive_down_mirror_widget_1)) {
        QMessageBox::critical(this, tr("Critical"), tr("The first station arrive screens is empty"), QMessageBox::Yes);
        return;
    }

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");

        QString uiType = list.at(ParamType);
        if (uiType.contains(ArriveFlag) && (1 != list.at(2).toInt())) {
            //非第1站到站界面
            EditWidget *edit = qobject_cast<EditWidget *>(it.value());
            if (NULL == edit)
                return;

            QVector<ViewObjectInfo*> vector_data;
            bool isMirror = filename.contains("mirror");
            int runDirAndMirror = (UP == list.at(ParamRunDir).toInt()) ? (isMirror ? 2 : 1) : (isMirror ? 4 : 3);

            switch (runDirAndMirror) {
            case 1: //上行非镜像
                vector_data = arrive_up_widget_1->GetWidgetVectorData();
                break;
            case 2: //上行镜像
                vector_data = arrive_up_mirror_widget_1->GetWidgetVectorData();
                break;
            case 3: //下行非镜像
                vector_data = arrive_down_widget_1->GetWidgetVectorData();
                break;
            case 4: //下行镜像
                vector_data = arrive_down_mirror_widget_1->GetWidgetVectorData();
                break;
            default:
                break;

            }

            for (int i = 0; i < vector_data.size(); i++)
            {
                QString id = edit->CopyArriveFromStationOne(vector_data[i]);
                if (id != "")
                {
                    struture_widget->AddData(edit->GetFileName(), id, vector_data[i]->object->GetObjectParam()->GetName(),
                                                                    vector_data[i]->object->GetObjectParam()->GetStId());
                }
            }
        }
    }
}


void MainWindow::SaveJson()
{
    //按V1.4.5版本配置文件存储，旧配置文件会被强制转换为新配置文件
    Json::Value jsonRoot;
    Json::Value jsonItem;
    QString version = qApp->applicationVersion();
    jsonItem["Version"] = version.toStdString();
    jsonItem["name"]   = myapp::mDynamicMapParam->m_project_name.toStdString();
    jsonItem["height"] = myapp::mDynamicMapParam->m_height;
    jsonItem["width"]  = myapp::mDynamicMapParam->m_width;
    jsonItem["interval_cur"] = myapp::mDynamicMapParam->m_interval_cur_station_pos;
    jsonItem["interval_station_num"] = myapp::mDynamicMapParam->m_interval_station_num;
    jsonItem["unequal_spacing_offset"] = myapp::mDynamicMapParam->m_unequal_spacing_offset;
    jsonItem["interval_unequal_spacing_offset"] = myapp::mDynamicMapParam->m_interval_unequal_spacing_offset;

    //只按“all_lines”方式存放线路信息
    Json::Value allLines;
    for (int m = 0; m < myapp::mDynamicMapParam->mLineInfoVector.length(); m ++) {
        const LineInfo &line = myapp::mDynamicMapParam->mLineInfoVector.at(m);
        Json::Value lineItem;
        lineItem["begin_x"] = line.begin_x;
        lineItem["begin_y"] = line.begin_y;
        lineItem["end_x"] = line.end_x;
        lineItem["end_y"] = line.end_y;
        lineItem["station_num"] = line.station_num;
        lineItem["staggered"] = myapp::getStaggeredFromInt(line.staggerd);
        lineItem["name_offset"] = myapp::getNameOffsetFromQPoint(line.name_offset);
        allLines.append(lineItem);
    }
    jsonItem["all_lines"] = allLines;

    jsonItem["interval_begin_x"] = myapp::mDynamicMapParam->m_interval_begin_x;
    jsonItem["interval_begin_y"] = myapp::mDynamicMapParam->m_interval_begin_y;
    jsonItem["interval_end_x"] = myapp::mDynamicMapParam->m_interval_end_x;
    jsonItem["interval_end_y"] = myapp::mDynamicMapParam->m_interval_end_y;

    jsonItem["mirror"] = myapp::mDynamicMapParam->m_has_mirror;
    jsonItem["down"] = myapp::mDynamicMapParam->m_has_down;
    jsonItem["next_time"] = myapp::mDynamicMapParam->m_next_time;

    jsonItem["interval_name_width"] = myapp::mDynamicMapParam->m_interval_station_data.station_width;
    jsonItem["interval_name_height"] = myapp::mDynamicMapParam->m_interval_station_data.station_height;
    jsonItem["interval_point_width"] = myapp::mDynamicMapParam->m_interval_station_data.point_width;
    jsonItem["interval_point_height"] = myapp::mDynamicMapParam->m_interval_station_data.point_height;
    jsonItem["interval_line_width"] = myapp::mDynamicMapParam->m_interval_station_data.line_width;
    jsonItem["interval_line_height"] = myapp::mDynamicMapParam->m_interval_station_data.line_height;

    jsonItem["name_width"] = myapp::mDynamicMapParam->m_station_data.station_width;
    jsonItem["name_height"] = myapp::mDynamicMapParam->m_station_data.station_height;
    jsonItem["point_width"] = myapp::mDynamicMapParam->m_station_data.point_width;
    jsonItem["point_height"] = myapp::mDynamicMapParam->m_station_data.point_height;
    jsonItem["line_width"] = myapp::mDynamicMapParam->m_station_data.line_width;
    jsonItem["line_height"] = myapp::mDynamicMapParam->m_station_data.line_height;

    if (myapp::mDynamicMapParam->m_type == DRM)
        jsonItem["type"] = "DRM";
    else
        jsonItem["type"] = "LCD";

    jsonItem["interval_staggered"] = myapp::getStaggeredFromInt(myapp::mDynamicMapParam->m_interval_staggered);
    jsonItem["interval_name_offset"] = myapp::mDynamicMapParam->m_interval_name_offset;

    jsonRoot.append(jsonItem);
    QString json_name = QString("%1/%2.json").arg(myapp::mDynamicMapParam->m_project_path).arg(myapp::mDynamicMapParam->m_project_name);
    std::string path = json_name.toLocal8Bit().data();
    ofstream ofs(path, ios::binary);
    if (ofs.is_open())
    {
        ofs << jsonItem.toStyledString();
        ofs.close();
    } else
    {
        QMessageBox::critical(this, tr("error"), tr("open json file error"));
    }
}

void MainWindow::create_project()
{
    GuideWidget *dlg = new GuideWidget;
    if (dlg->exec() == QDialog::Accepted)
    {
        //创建项目文件夹
        QString new_path = QString("%1/%2").arg(myapp::mDynamicMapParam->m_project_path)
                                           .arg(myapp::mDynamicMapParam->m_project_name);

        QFileInfo folder_info(new_path);
        if (folder_info.isDir())//已存在 则清空原有文件夹内容
        {
            QDir  dir(new_path);

            QDirIterator DirsIterator(new_path, QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot, QDirIterator::NoIteratorFlags);
            while (DirsIterator.hasNext())
            {
                if (!dir.remove(DirsIterator.next())) //删除文件操作如果返回否，那它就是目录
                {
                     QDir(DirsIterator.filePath()).removeRecursively(); //删除目录本身以及它下属所有的文件及目录
                }
            }
        }
        else//没有 创建项目文件夹
        {
            QDir folder(myapp::mDynamicMapParam->m_project_path);
            createFoler(&folder, new_path);
        }

        myapp::mDynamicMapParam->m_project_path = new_path;

        SaveJson();
        //创建相关文件夹
        createSourceFilder();

        //生成左上角树形结构
        station_widget->GenerateTree();
        station_widget->expandAll();

        //创建所有XML文件编辑器
        createEditWidgets();

        //自动生成界面(仅上行非镜像)
        GenerateRoute();

        config_widget->InitConfig();//初始化配置窗口，并显示配置数据

        component_widget->show_list_widget();//显示控件列表

        saveaAllProject();//保存全部数据
    }
}

void MainWindow::create_file()
{
    bool isOk;
    QString name = QInputDialog::getText(this, tr("New File"), tr("Please input new file name"), QLineEdit::Normal, "", &isOk);
    if (!isOk) {
        return;
    }
    if (name.right(4) != ".xml") {
        QMessageBox::warning(this, tr("Warning"), tr("The file name must end with .xml"), QMessageBox::Yes);
        return;
    }

    if (myapp::mDynamicMapParam->mMapObjectShow.contains(name)) {
        QMessageBox::critical(this, tr("Critical"), tr("File name already exists"), QMessageBox::Yes);
        return;
    }

    //创建文件编辑器
    EditWidget *edit = new EditWidget(name, QSize(myapp::mDynamicMapParam->m_width, myapp::mDynamicMapParam->m_height));
    if (edit) {
        edit->setPath(myapp::mDynamicMapParam->m_project_path);
        edit->setVisible(false);
        edit->savecfg();
        myapp::mDynamicMapParam->mMapObjectShow[name] = edit;

        //生成左上角树形结构
        station_widget->GenerateTree();
        station_widget->expandAll();
    }
}

QFileInfoList MainWindow::getFileList(const QString& sPath)
{
    QFileInfoList result;

    QDir dir(sPath);

    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::Dirs | QDir::NoDotAndDotDot);
    dir.setSorting(QDir::Time | QDir::Reversed);

    QFileInfoList fileInfoList = dir.entryInfoList();

    foreach (QFileInfo fileInfo, fileInfoList)
    {
        if (fileInfo.isDir())
            result.append(getFileList(fileInfo.filePath()));
        else
            result.append(fileInfo);
    }
    return result;
}

void MainWindow::GenerateEditFromXml(const QString& xml_path)
{
    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        EditWidget *edit = qobject_cast<EditWidget *>(it.value());
        edit->xml_to_vector(xml_path, it.key(), struture_widget);
    }
}

bool MainWindow::ParseProjectJsonFile(const QString& full_json_file_name, const QString& path_without_json_file_name)
{
    //支持中文路径
    std::string path = full_json_file_name.toLocal8Bit().data();
    ifstream ifs(path, ios::binary);
    if (!ifs.is_open())
    {
        QMessageBox::critical(this, tr("error"), tr("open json file error"));
        return false;
    }

    Json::Value jsonRoot;
    Json::Reader jsonReader;
    if (!jsonReader.parse(ifs, jsonRoot))
    {
        QMessageBox::warning(this, QObject::tr("waring"), QObject::tr("cannot found project json file"));
        return false;
    }
    ifs.close();

//    if (jsonRoot["name"].isNull() ||
//        jsonRoot["type"].isNull() || jsonRoot["line_type"].isNull() ||
//        jsonRoot["height"].isNull() || jsonRoot["width"].isNull() ||
//        jsonRoot["down"].isNull() || jsonRoot["mirror"].isNull() ||
//        jsonRoot["all_station_num"].isNull() || jsonRoot["interval_station_num"].isNull() ||
//        jsonRoot["interval_cur"].isNull() || jsonRoot["multiline"].isNull() ||
//        jsonRoot["all_staggered"].isNull() || jsonRoot["interval_staggered"].isNull() ||
//        jsonRoot["unequal_spacing_offset"].isNull() || jsonRoot["interval_unequal_spacing_offset"].isNull() ||
//        jsonRoot["station_interval"].isNull() || jsonRoot["interval_station_interval"].isNull() ||
//        jsonRoot["begin_x"].isNull() || jsonRoot["begin_y"].isNull() || jsonRoot["next_time"].isNull() ||
//        jsonRoot["interval_begin_x"].isNull() || jsonRoot["interval_begin_y"].isNull())
//    {
//        QMessageBox::warning(this, QObject::tr("waring"), QObject::tr("parse json file failed"));
//        return false;
//    }

    if (jsonRoot["Version"].isNull()) {
        //找不到版本号暂时不报错
        //QMessageBox::warning(this, QObject::tr("waring"), QObject::tr("Version is loss in project file"));
        //return false;
    }

    myapp::mDynamicMapParam->m_project_name = QString::fromStdString(jsonRoot["name"].asString());
    myapp::mDynamicMapParam->m_project_path = path_without_json_file_name;
    myapp::mDynamicMapParam->m_height = jsonRoot["height"].asInt();
    myapp::mDynamicMapParam->m_width = jsonRoot["width"].asInt();
    myapp::mDynamicMapParam->m_has_mirror = jsonRoot["mirror"].asBool();
    myapp::mDynamicMapParam->m_has_down = jsonRoot["down"].asBool();
    myapp::mDynamicMapParam->m_next_time = jsonRoot["next_time"].asBool();


    myapp::mDynamicMapParam->m_unequal_spacing_offset = jsonRoot["unequal_spacing_offset"].asInt();

    myapp::mDynamicMapParam->m_interval_cur_station_pos = jsonRoot["interval_cur"].asInt();
    myapp::mDynamicMapParam->m_interval_station_num = jsonRoot["interval_station_num"].asInt();
    myapp::mDynamicMapParam->m_interval_unequal_spacing_offset = jsonRoot["interval_unequal_spacing_offset"].asInt();
    myapp::mDynamicMapParam->m_interval_staggered = myapp::getStaggeredFromString(jsonRoot["interval_staggered"].asString());
    if (jsonRoot["interval_name_offset"].isNull()) {
        myapp::mDynamicMapParam->m_interval_name_offset = 0;
    } else {
        myapp::mDynamicMapParam->m_interval_name_offset = jsonRoot["interval_name_offset"].asInt();
    }

    myapp::mDynamicMapParam->m_interval_begin_x = jsonRoot["interval_begin_x"].asInt();
    myapp::mDynamicMapParam->m_interval_begin_y = jsonRoot["interval_begin_y"].asInt();
    if (!jsonRoot["interval_station_interval"].isNull()) {
        // <=V1.4.4
        int length = jsonRoot["interval_station_interval"].asInt();
        myapp::mDynamicMapParam->m_interval_end_x = myapp::mDynamicMapParam->m_interval_begin_x + length;
        myapp::mDynamicMapParam->m_interval_end_y = myapp::mDynamicMapParam->m_interval_begin_y;
    } else {
        // >=V1.4.5
        myapp::mDynamicMapParam->m_interval_end_x = jsonRoot["interval_end_x"].asInt();
        myapp::mDynamicMapParam->m_interval_end_y = jsonRoot["interval_end_y"].asInt();
    }
    myapp::mDynamicMapParam->m_station_data.station_width = jsonRoot["name_width"].asInt();
    myapp::mDynamicMapParam->m_station_data.station_height = jsonRoot["name_height"].asInt();
    myapp::mDynamicMapParam->m_station_data.point_width = jsonRoot["point_width"].asInt();
    myapp::mDynamicMapParam->m_station_data.point_height = jsonRoot["point_height"].asInt();
    myapp::mDynamicMapParam->m_station_data.line_width = jsonRoot["line_width"].asInt();
    myapp::mDynamicMapParam->m_station_data.line_height = jsonRoot["line_height"].asInt();

    myapp::mDynamicMapParam->m_interval_station_data.station_width = jsonRoot["interval_name_width"].asInt();
    myapp::mDynamicMapParam->m_interval_station_data.station_height = jsonRoot["interval_name_height"].asInt();
    myapp::mDynamicMapParam->m_interval_station_data.point_width = jsonRoot["interval_point_width"].asInt();
    myapp::mDynamicMapParam->m_interval_station_data.point_height = jsonRoot["interval_point_height"].asInt();
    myapp::mDynamicMapParam->m_interval_station_data.line_width = jsonRoot["interval_line_width"].asInt();
    myapp::mDynamicMapParam->m_interval_station_data.line_height = jsonRoot["interval_line_height"].asInt();

    if (jsonRoot["all_lines"].isNull()) {
        // <=V1.4.4 兼容打开旧版本项目，只支持一条线段配置
        LineInfo line;
        line.begin_x = jsonRoot["begin_x"].asInt();
        line.begin_y = jsonRoot["begin_y"].asInt();
        line.station_num = jsonRoot["all_station_num"].asInt();
        int length = jsonRoot["station_interval"].asInt();
        line.end_x = line.begin_x + length;
        line.end_y = line.begin_y;
        line.staggerd = myapp::getStaggeredFromString(jsonRoot["all_staggered"].asString());
        line.name_offset = QPoint(0, 0);
        myapp::mDynamicMapParam->mLineInfoVector.push_back(line);
    } else {
        // >=V1.4.5 支持多线段配置
        for (Json::ArrayIndex index = 0; index < jsonRoot["all_lines"].size(); index ++) {
            Json::Value &val = jsonRoot["all_lines"][index];
            LineInfo line;
            line.begin_x = val["begin_x"].asInt();
            line.begin_y = val["begin_y"].asInt();
            line.station_num = val["station_num"].asInt();
            line.end_x = val["end_x"].asInt();
            line.end_y = val["end_y"].asInt();
            line.staggerd = myapp::getStaggeredFromString(val["staggered"].asString());
            line.name_offset = myapp::getNameOffsetFromString(val["name_offset"].asString());
            myapp::mDynamicMapParam->mLineInfoVector.push_back(line);
        }
    }
    int stationNums = 0;
    for (int m = 0; m < myapp::mDynamicMapParam->mLineInfoVector.length(); m ++) {
        const LineInfo &line = myapp::mDynamicMapParam->mLineInfoVector.at(m);
        stationNums += line.station_num;
    }
    myapp::mDynamicMapParam->m_station_total = stationNums;

    if (QString::fromStdString(jsonRoot["type"].asString()) == "DRM")
        myapp::mDynamicMapParam->m_type = DRM;
    else
        myapp::mDynamicMapParam->m_type = LCD;

    return true;
}

void MainWindow::open_project(QString jsonFile)
{
    /*
        此处有两种做法(目前选择第2种)
        1、打开文件夹，之后自动读取与文件夹同名的json文件，若不存在就报错返回
        2、直接打开某一文件，之后在相应的目录下寻找xml和img资源，找不到就错误返回

    */

    QString all_path;
    if (jsonFile.isEmpty())
    {
        QString title = QObject::tr("please select a json file");
        all_path = QFileDialog::getOpenFileName(this, title, "", "Json File(*.json)");
        //获取文件全路径，包含文件名   E:/dymap-edit/hang2/hang2.json
        if (all_path == "" || !myapp::isFileExist(all_path))
            return;

    } else
    {
        all_path = jsonFile;
    }

    QFileInfo fileInfo = all_path;

    //项目文件夹不包含文件名   E:/dymap-edit/hang2
    QString path = fileInfo.path();//filePath是全路径 

    QDir dir(path);
    if (!dir.cdUp())
        return;

    QString xml_path = path + QString("/xml/");

    QDir xml_dir(xml_path);
    if (!xml_dir.exists())
    {
        QMessageBox::critical(this, tr("error"), tr("cannot found xml folder"));
        return;
    }

    if (!ParseProjectJsonFile(all_path, path))
        return;

    QFileInfoList list = getFileList(xml_path);

    int size = list.size();

    for (int i = 0; i < size; ++i)
    {
        QFileInfo fileInfo = list.at(i);
        QStringList filename_list = fileInfo.fileName().split("_");
        //过滤所有all界面类型的变种界面
        if (filename_list.at(ParamType).contains(AllFlag) && filename_list.at(ParamType) != AllFlag)
            continue;
        myapp::mDynamicMapParam->mMapObjectShow[fileInfo.fileName()] = NULL;
    }

    station_widget->GenerateTree();//生产xml列表

    createEditWidgets();//创建所有XML文件编辑器

    GenerateEditFromXml(xml_path);//将xml信息转化成map存储

    config_widget->InitConfig();//初始化线路设置控件信息

    component_widget->show_list_widget();//显示控件列表

    station_widget->expandAll();//全部打开

    //show_widget->add_right_click_action_refresh();//添加刷新界面的右击按钮

}

void MainWindow::show_component()
{
     for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
     {
         EditWidget *edit = qobject_cast<EditWidget *>(it.value());
         if (edit)
             edit->show_component();
     }
}

bool MainWindow::createFoler(QDir *folder, QString file_name)
{
    bool res = false;
    res = folder->mkpath(file_name);
    return res;
}


void MainWindow::saveaAllProject()
{
    auto it = myapp::mDynamicMapParam->mMapObjectShow.begin();
    while(it != myapp::mDynamicMapParam->mMapObjectShow.end())
    {
        if (it.value())
        {
             EditWidget *Edit = qobject_cast< EditWidget *>(it.value());
             if (Edit) Edit->savecfg();
        }
        it++;
    }
    SaveJson();
}

void MainWindow::AutoGenerateFromUp()
{
    //只处理全线路图和区间图
    //清空镜像和下行的所有edit上的控件，并重新根据上行生成，适合上行增删控件或者大面积改位置之后重新生成
    LOG_QDEBUG << myapp::mDynamicMapParam->mMapObjectShow.size();
    if (myapp::mDynamicMapParam->mMapObjectShow.size() == 0)
        return;

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        LOG_QDEBUG << it.key();
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");

        QString uiType = list.at(ParamType);
        if (uiType.contains(AllFlag) || uiType.contains(IntervalFlag)) {
            if (DOWN == list.at(ParamRunDir).toInt() || filename.contains("mirror")) {
                if (it.value())
                {
                    EditWidget *edit = qobject_cast<EditWidget *>(it.value());
                    if (edit == NULL) continue;
                    edit->ClearVector();
                    struture_widget->DeleteStructureData(it.key());
                    attribute_widget->cancel_attribute();
                }
            }
        }
    }
    GenerateRunDown();
    GenerateMirror();
}

void MainWindow::AutoGenerateArriveOneFromUp()
{
    //只处理第一个站点的到站图
    //清空镜像和下行的所有edit上的控件，并重新根据上行生成，适合上行增删控件或者大面积改位置之后重新生成
    LOG_QDEBUG << myapp::mDynamicMapParam->mMapObjectShow.size();
    if (myapp::mDynamicMapParam->mMapObjectShow.size() == 0)
        return;

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        LOG_QDEBUG << it.key();
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");

        QString uiType = list.at(ParamType);
        if (uiType.contains(ArriveFlag))
        {
            if (DOWN == list.at(ParamRunDir).toInt() || filename.contains("mirror")) {
                if (it.value())
                {
                    EditWidget *edit = qobject_cast<EditWidget *>(it.value());
                    if (edit == NULL) continue;
                    edit->ClearVector();
                    struture_widget->DeleteStructureData(it.key());
                    attribute_widget->cancel_attribute();
                }
            }
        }
    }

    GenerateRunDownArriveOne();
    GenerateMirrorArriveOne();
}

void MainWindow::save_project()
{
    saveaAllProject();
}

//创建控件
void MainWindow::slt_create_item(ObjectInfo param, QPoint pos)
{
    if (mCurrShowFilename == "")
        return;
    //正常单独控件是取name   如TimeView取time    NextView取next
    QString struct_show_item_name = param.object_name.toLower().left(param.object_name.size() - 4);

    //若是SingleView则会取single1 single2 等等，数字代表此幅图出现的SingleView的次数
    QString random = show_widget->CreateItem(param, pos, struct_show_item_name);
    if (random == "")
        return;
    struture_widget->CreateStructure(mCurrShowFilename, struct_show_item_name, random);
}

void MainWindow::GetSrcSize(const QString flag, AutoData *data)
{
    data->pos = QPoint(0, 0);

    if (flag == AllFlag)
    {
        data->point_height   = myapp::mDynamicMapParam->m_station_data.point_height;
        data->point_width    = myapp::mDynamicMapParam->m_station_data.point_width;
        data->station_height = myapp::mDynamicMapParam->m_station_data.station_height;
        data->station_width  = myapp::mDynamicMapParam->m_station_data.station_width;
        data->line_height    = myapp::mDynamicMapParam->m_station_data.line_height;
        data->line_width     = myapp::mDynamicMapParam->m_station_data.line_width;
    } else if (flag == IntervalFlag)
    {
        data->point_height   = myapp::mDynamicMapParam->m_interval_station_data.point_height;
        data->point_width    = myapp::mDynamicMapParam->m_interval_station_data.point_width;
        data->station_height = myapp::mDynamicMapParam->m_interval_station_data.station_height;
        data->station_width  = myapp::mDynamicMapParam->m_interval_station_data.station_width;
        data->line_height    = myapp::mDynamicMapParam->m_interval_station_data.line_height;
        data->line_width     = myapp::mDynamicMapParam->m_interval_station_data.line_width;
    }
}

void MainWindow::AddSingleView(int x, int y, int w, int h, QString object_name, EditWidget *edit, QString file_name)
{
    //返回带id的singleview，其他控件正常返回name
    QString struct_show_type_name = object_name.toLower().left(object_name.size() - 4);
    QString random =  edit->AutoGenerate(object_name, struct_show_type_name, myapp::to_mid(QPoint(x, y), w, h), w, h);
    if (random != "")
        struture_widget->AddData(file_name, random, struct_show_type_name, 0);
}

void MainWindow::ReloadMainWayFromConfig()
{
    //清空镜像和下行的所有edit上的控件，并重新根据上行生成，适合上行增删控件或者大面积改位置之后重新生成
    LOG_QDEBUG << myapp::mDynamicMapParam->mMapObjectShow.size();

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        LOG_QDEBUG << it.key();
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");
        if (!it.value())
            continue;

        QString uiType = list.at(ParamType);
        if (uiType.contains(AllFlag) || uiType.contains(IntervalFlag)) {
            if (DOWN == list.at(ParamRunDir).toInt() || filename.contains("mirror")) {
                //上行镜像、下行非镜像、下行镜像图清空所有控件
                if (it.value())
                {
                    EditWidget *edit = qobject_cast<EditWidget *>(it.value());
                    if (edit == NULL) continue;
                    edit->ClearVector();
                    struture_widget->DeleteStructureData(it.key());
                    attribute_widget->cancel_attribute();
                }
            } else {
                //上行非镜像只清空主线路控件：PointView、LineView、StationView
                EditWidget *edit = qobject_cast<EditWidget *>(it.value());
                if (edit == NULL) continue;
                edit->ClearMainWayVector();
                struture_widget->DeleteMainWayStructureData(it.key());
                attribute_widget->cancel_attribute();
            }
        }
    }

    //重新生成上行主线路
    ReloadMainWay();

    //重新生成之后需要重新绑定点击信号
    struture_widget->ShowStructue(mCurrShowFilename);

    //更新当前图
    show_widget->getEditWidget()->show_component();
}


void MainWindow::ReloadMainWay()
{
    //默认生成上行、非镜像的xml文件
    if (myapp::mDynamicMapParam->m_type != DRM)
        return;

    int interval_begin_x = myapp::mDynamicMapParam->m_interval_begin_x;
    int interval_begin_y = myapp::mDynamicMapParam->m_interval_begin_y;
    int interval_end_x = myapp::mDynamicMapParam->m_interval_end_x;
    int interval_station_num = myapp::mDynamicMapParam->m_interval_station_num;
    Staggered interval_staggered = (Staggered)myapp::mDynamicMapParam->m_interval_staggered;
    int interval_name_offset = myapp::mDynamicMapParam->m_interval_name_offset;

    int stationSpacing = 0;
    Staggered staggered;
    int station_num;
    AutoData pnl_size;//point name line size

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");
        if (!it.value())
            continue;

        QString uiType = list.at(ParamType);
        if (ZERO == uiType.compare(AllFlag) && (!myapp::mDynamicMapParam->mLineInfoVector.isEmpty())) {
            //全线路
            if ((UP == list.at(ParamRunDir).toInt()) && (!filename.contains("mirror"))) {
                //只生成上行非镜像界面
                GetSrcSize(AllFlag, &pnl_size);
                int beginX = 0, beginY = 0, endX = 0, endY = 0, lineLength = 0;
                QPoint nameOffset(0, 0);
                int lineIndex = 1;
                int startStationId = 1;
                int currStationTotal = 0;
                for (int m = 0; m < myapp::mDynamicMapParam->mLineInfoVector.length(); m ++) {
                    const LineInfo &line = myapp::mDynamicMapParam->mLineInfoVector.at(m);
                    beginX = line.begin_x;
                    beginY = line.begin_y;
                    endX = line.end_x;
                    endY = line.end_y;
                    staggered = (Staggered)line.staggerd;
                    station_num = line.station_num;
                    nameOffset = line.name_offset;
                    lineIndex = m + 1;
                    startStationId = currStationTotal + 1;
                    currStationTotal += station_num;
                    if (station_num < 2) {
                        LOG_QDEBUG << "每条线路的站点数不能小于2";
                        return;
                    }
                    //线路长度为：终点X坐标-起点X坐标，正数表示向右，负数表示向左，不可能为0
                    lineLength = endX - beginX;
                    if (0 == lineLength) {
                        LOG_QDEBUG << "线路长度不能为0";
                        return;
                    }
                    stationSpacing = lineLength / (station_num - 1);
                    AutoData data[station_num + 1];

                    for (int i = 0; i < station_num; i++)
                    {
                        data[i] = pnl_size;
                        if (i == 0)
                            data[i].pos = QPoint(beginX, beginY);
                        else
                            data[i].pos = data[i-1].pos + QPoint(stationSpacing, 0);
                    }
                    data[station_num].pos = QPoint(-1, -1);

                    //在edit上存放点控件
                    EditWidget *edit = qobject_cast<EditWidget *>(it.value());
                    if (edit == NULL)
                        continue;
                    QMap<QString, QString> stationview_map_point = edit->GenerateForStationView("PointView", data, staggered, station_num, lineIndex,
                                                                                      startStationId, stationSpacing, nameOffset);
                    for (auto point_it = stationview_map_point.begin(); point_it != stationview_map_point.end(); point_it++)
                    {
                        if (point_it.key() != "" && point_it.value() != "")
                            struture_widget->AddData(it.key(), point_it.key(), point_it.value(),
                                                     point_it.value().right(point_it.value().size()-5).toInt());
                    }

                    if (myapp::mDynamicMapParam->m_next_time)
                    {
                        QMap<QString, QString> stationview_map_arrive_time = edit->GenerateForStationView("EtaView", data, staggered, station_num, lineIndex,
                                                                                                startStationId, stationSpacing, nameOffset);
                        for (auto arrive_time_it = stationview_map_arrive_time.begin(); arrive_time_it != stationview_map_arrive_time.end(); arrive_time_it++)
                        {
                            if (arrive_time_it.key() != "" && arrive_time_it.value() != "")
                                struture_widget->AddData(it.key(), arrive_time_it.key(), arrive_time_it.value(),
                                                         arrive_time_it.value().right(arrive_time_it.value().size()-3).toInt());
                        }
                    }

                    QMap<QString, QString> stationview_map_name = edit->GenerateForStationView("StationView", data, staggered, station_num, lineIndex,
                                                                                     startStationId, stationSpacing, nameOffset);
                    for (auto name_it = stationview_map_name.begin(); name_it != stationview_map_name.end(); name_it++)
                    {
                        if (name_it.key() != "" && name_it.value() != "")
                            struture_widget->AddData(it.key(), name_it.key(), name_it.value(),
                                                     name_it.value().right(name_it.value().size()-7).toInt());
                    }

                    QMap<QString, QString> stationview_map_line = edit->GenerateForStationView("LineView", data, staggered, station_num, lineIndex,
                                                                                     startStationId, stationSpacing, nameOffset);
                    for (auto line_it = stationview_map_line.begin(); line_it != stationview_map_line.end(); line_it++)
                    {
                        if (line_it.key() != "" && line_it.value() != "")
                            struture_widget->AddData(it.key(), line_it.key(), line_it.value(),
                                                     line_it.value().right(line_it.value().size()-4).toInt());
                    }
                }
            }
        } else if (ZERO == uiType.compare(IntervalFlag) && (0 != interval_begin_x)) {
                //区间图
            if ((UP == list.at(ParamRunDir).toInt()) && (!filename.contains("mirror"))) {
                //只生成上行非镜像界面
                GetSrcSize(IntervalFlag, &pnl_size);

                int lineLength = 0;
                //线路长度为：终点X坐标-起点X坐标，正数表示向右，区间图只能为正数
                lineLength = interval_end_x - interval_begin_x;
                if (lineLength <= 0) {
                    LOG_QDEBUG << "线路长度必须为正数";
                    return;
                }
                stationSpacing = lineLength / (interval_station_num -1);

                station_num = interval_station_num;
                staggered = interval_staggered;
                AutoData data[station_num + 1];

                for (int i = 0; i < station_num; i++)
                {
                    data[i] = pnl_size;
                    //设置data[i].point这里的point不是指点的位置，是指整体的x，y坐标，如果是站点名的y值还会根据m_staggered去改变
                    if (i == 0)
                        data[i].pos = QPoint(interval_begin_x, interval_begin_y);
                    else
                        data[i].pos = data[i-1].pos + QPoint(stationSpacing, 0);
                }
                data[station_num].pos = QPoint(-1, -1);

                //在edit上存放点控件
                EditWidget *edit = qobject_cast<EditWidget *>(it.value());
                if (edit == NULL)
                    continue;
                QMap<QString, QString>  stationview_map_name = edit->GenerateForStationViewInterval("StationView", data, staggered, station_num, interval_name_offset);
                for (auto name_it = stationview_map_name.begin(); name_it != stationview_map_name.end(); name_it++)
                {
                    if (name_it.key() != "" && name_it.value() != "")
                        struture_widget->AddData(it.key(), name_it.key(), name_it.value(),
                                                 name_it.value().right(name_it.value().size()-7).toInt());
                }

                QMap<QString, QString>  stationview_map_point = edit->GenerateForStationViewInterval("PointView", data, staggered, station_num, interval_name_offset);
                for (auto point_it = stationview_map_point.begin(); point_it != stationview_map_point.end(); point_it++)
                {
                    if (point_it.key() != "" && point_it.value() != "")
                        struture_widget->AddData(it.key(), point_it.key(), point_it.value(),
                                                 point_it.value().right(point_it.value().size()-5).toInt());
                }
                QMap<QString, QString>  stationview_map_line = edit->GenerateForStationViewInterval("LineView", data, staggered, station_num, interval_name_offset);
                for (auto line_it = stationview_map_line.begin(); line_it != stationview_map_line.end(); line_it++)
                {
                    if (line_it.key() != "" && line_it.value() != "")
                        struture_widget->AddData(it.key(), line_it.key(), line_it.value(),
                                                 line_it.value().right(line_it.value().size()-4).toInt());

                }
            }
        } else {
            //全线路及区间图的变种暂不考虑
        }
    }
}

void MainWindow::GenerateRoute()
{
    int app_w = myapp::mDynamicMapParam->m_width;
    int app_h = myapp::mDynamicMapParam->m_height;

    //默认添加一个SingleView用于设置背景图
    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        EditWidget *edit = qobject_cast<EditWidget *>(it.value());
        if (edit == NULL)
            continue;
        AddSingleView(0, 0, app_w, app_h, "SingleView", edit, it.key());
    }

    //重新生成上行非镜像线路
    ReloadMainWay();
}

void MainWindow::GenerateRunDown()
{
    if (myapp::mDynamicMapParam->m_type != DRM)
        return;

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");

        QString uiType = list.at(ParamType);
        if (uiType.contains(AllFlag) || uiType.contains(IntervalFlag)) {
            if (DOWN == list.at(ParamRunDir).toInt() && (!filename.contains("mirror"))) {
                //替换下行为上行
                list[ParamRunDir] = "1";
                QString upFilename = list.join('_');
                CopyRunDown(QString("%1.xml").arg(upFilename), it.value());
            }
        }
    }
}

void MainWindow::GenerateRunDownArriveOne()
{
    if (myapp::mDynamicMapParam->m_type != DRM)
        return;

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");

        QString uiType = list.at(ParamType);
        if (uiType.contains(ArriveFlag))
        {
            if (DOWN == list.at(ParamRunDir).toInt() && (!filename.contains("mirror"))) {
                //替换下行为上行
                list[ParamRunDir] = "1";
                QString upFilename = list.join('_');
                CopyRunDown(QString("%1.xml").arg(upFilename), it.value());
            }
        }
    }
}

void MainWindow::GenerateMirrorArriveOne()
{
    if (myapp::mDynamicMapParam->m_type != DRM)
        return;

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");

        QString uiType = list.at(ParamType);
        if (uiType.contains(ArriveFlag))
        {
            if (filename.contains("mirror")) {
                int index = filename.indexOf("mirror");
                CopyMirror(QString("%1.xml").arg(filename.left(index - 1)), it.value());
            }
        }
    }
}

void MainWindow::GenerateMirror()
{
    if (myapp::mDynamicMapParam->m_type != DRM)
        return;

    for (auto it = myapp::mDynamicMapParam->mMapObjectShow.begin(); it != myapp::mDynamicMapParam->mMapObjectShow.end(); it++)
    {
        QString filename = it.key().left(it.key().size() - 4);
        QStringList list = filename.split("_");

        QString uiType = list.at(ParamType);
        if (uiType.contains(AllFlag) || uiType.contains(IntervalFlag)) {
            if (filename.contains("mirror")) {
                int index = filename.indexOf("mirror");
                CopyMirror(QString("%1.xml").arg(filename.left(index - 1)), it.value());
            }
        }
    }
}

void MainWindow::CopyRunDown(QString up_name, QWidget *widget)
{
    if (up_name == "")
        return;
    if (NULL == widget)
        return;

    QWidget *up_widget = myapp::mDynamicMapParam->mMapObjectShow[up_name];
    EditWidget *up_edit = qobject_cast<EditWidget *>(up_widget);
    EditWidget *edit = qobject_cast<EditWidget *>(widget);

    if (up_edit && edit) {
        QVector<ViewObjectInfo*> vector_data = up_edit->GetWidgetVectorData();
        for (int i = 0; i < vector_data.size(); i++)
        {
            QString id = edit->updata2downdata(vector_data[i]);
            if (id != "")
            {
                struture_widget->AddData(edit->GetFileName(), id, vector_data[i]->object->GetObjectParam()->GetName(),
                                         vector_data[i]->object->GetObjectParam()->GetStId());
            }
        }
    }
}

void MainWindow::CopyMirror(QString nonmirror_name, QWidget *widget)
{
    if (nonmirror_name == "")
        return;
    if (NULL == widget)
        return;

    QWidget *nonmirror_widget = myapp::mDynamicMapParam->mMapObjectShow[nonmirror_name];
    EditWidget *nonmirror_edit = qobject_cast<EditWidget *>(nonmirror_widget);
    EditWidget *edit = qobject_cast<EditWidget *>(widget);

    if (nonmirror_edit && edit)
    {
        QVector<ViewObjectInfo*> vector_data = nonmirror_edit->GetWidgetVectorData();
        for (int i = 0; i < vector_data.size(); i++)
        {
            QString id = edit->original2mirror(vector_data[i], nonmirror_name);
            if (id != "")
            {
                struture_widget->AddData(edit->GetFileName(), id, vector_data[i]->object->GetObjectParam()->GetName(),
                                         vector_data[i]->object->GetObjectParam()->GetStId());
            }
        }
    }
}

